<template> 
  <el-card class="form-container" shadow="never">
    <el-form :model="role" :rules="rules" ref="roleFrom" label-width="150px">
      <el-form-item label="角色名：" prop="name">
        <el-input v-model="role.name"></el-input>
      </el-form-item>
      <el-form-item label="备注：">
        <el-input v-model="role.remark"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('roleFrom')">提交</el-button>
        <el-button v-if="!isEdit" @click="resetForm('roleFrom')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
  import {addRole,updateRole,getRole} from '@/api/role'
  const defaultRole={
    id:null,
    name: '',
    remark: '',
    isDefaultRole:false
  };
  export default {
    name: 'UpdateRole',
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        role:Object.assign({}, defaultRole),
        rules: {
          name: [
            {required: true, message: '请输入角色名', trigger: 'blur'}
          ]
        }
      }
    },
    created() {
      this.role.id= this.$route.query.id;
      this.isEdit=this.role.id==null?false:true;
      if (this.isEdit) {
        getRole(this.role.id).then(response => {
          this.role = response.data;
        });
      }else{
        this.role = Object.assign({},defaultRole);
      }
    },
    methods: {
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('是否提交数据', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              if (this.isEdit) {
                updateRole(this.role).then(response => {
                  this.$refs[formName].resetFields();
                  this.$message({
                    message: '修改成功',
                    type: 'success',
                    duration:1000
                  });
                  this.$router.back();
                });
              } else {
                addRole(this.role).then(response => {
                  this.$refs[formName].resetFields();
                  this.role = Object.assign({},defaultRole);
                  this.$message({
                    message: '提交成功',
                    type: 'success',
                    duration:1000
                  });
                });
              }
            });

          } else {
            this.$message({
              message: '验证失败',
              type: 'error',
              duration:1000
            });
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.role = Object.assign({},defaultRole);
      }
    }
  }
</script>
<style>
</style>


